package com.sk.waste.app.activitys

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.Gravity
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.lc.smc.lib.annotations.LCBindView
import com.lc.smc.lib.interfaces.LCInterface
import com.lc.smc.lib.utils.LCBaseUtil
import com.lc.smc.lib.utils.LCLogger
import com.lc.smc.lib.utils.LCSPUtil
import com.sk.waste.app.R
import com.sk.waste.app.adapters.AlbumAdapter
import com.sk.waste.app.adapters.SliderAdapter
import com.sk.waste.app.adapters.SliderSpaceAdapter
import com.sk.waste.app.application.MyApplication
import com.sk.waste.app.bases.BaseActiivity
import com.sk.waste.app.config.AppConfig
import com.sk.waste.app.config.NetWorkConfig
import com.sk.waste.app.models.ImageModel
import com.sk.waste.app.models.SpaceModel
import com.sk.waste.app.models.TenderModel
import com.sk.waste.app.utils.BaseUtil
import com.sk.waste.app.utils.OkHttpUtil
import com.sk.waste.app.views.SkAlertDialog
import com.sking.album.activitys.ShowLargePicActivity
import com.sking.album.model.SKRImageModel
import com.sking.album.utils.SKRPhotoSelectUtil
import com.sking.album.view.AlbumSelectPopuWindow
import okhttp3.Call
import org.json.JSONObject
import java.io.IOException

/**
 *  @time 2025/10/22  10:32
 *  @author Im_jingwei
 *  @desc 发布信息
 */
class PushDetailActivity : BaseActiivity() {

    @LCBindView(R.id.ac_space_avatar)
    lateinit var imgAvatar: ImageView

    @LCBindView(R.id.ac_space_name)
    lateinit var ttvName: TextView

    @LCBindView(R.id.ac_space_vip)
    lateinit var imgVip: ImageView

    @LCBindView(R.id.ac_space_time)
    lateinit var ttvTime: TextView

    @LCBindView(R.id.ac_space_location)
    lateinit var ttvLocation: TextView

    @LCBindView(R.id.ac_space_banner)
    lateinit var imgBanner: ViewPager2

    @LCBindView(R.id.ac_space_look)
    lateinit var ttvLook: TextView

    @LCBindView(R.id.ac_space_call)
    lateinit var ttvCall: TextView

    @LCBindView(R.id.ac_space_content)
    lateinit var ttvContent: TextView

    var spaceDetail: SpaceModel? = null
    private val userInfo = MyApplication.instance.getUserInfo()

    override fun onCreate(savedInstanceState: Bundle?) {
        setContentView(R.layout.activity_push_detail)
        super.onCreate(savedInstanceState)
        setBack()
        setTitleView("空间详情")
        val spaceId = intent.getStringExtra("extral_pushid")
        getTenderDetail(spaceId)
    }

    private fun getTenderDetail(spaceId: String?) {
        if (spaceId.isNullOrEmpty()) {
            return
        }
        showProgress()
        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_SPACE_DETAIL + spaceId
        val token = LCSPUtil[mContext, AppConfig.SP_ACCESS_TOKEN]
        val httpUtil = OkHttpUtil()
        httpUtil.httpRequestGet(url, token, object : LCInterface.LcCallBackListener {
            override fun onFailure(call: Call, e: IOException) {
                cancleProgress()
                LCBaseUtil.showToast(mContext, "获取失败，" + e.message)
            }

            @Throws(IOException::class)
            override fun onSuccess(call: Call, response: String) {
                try {
                    cancleProgress()
                    val jsonObject = JSONObject(response)
                    val success = jsonObject.getBoolean("success")
                    val msg = jsonObject.getString("message")
                    val code = jsonObject.getInt("code")
                    val data = jsonObject.getJSONObject("data")
                    if (success) {
                        spaceDetail = SpaceModel().apply { getModelInfo(data) }
                        val imgArray = data.getJSONArray("imageList")
                        val list = ArrayList<ImageModel>()
                        for (i in 0 until imgArray.length()) {
//                            val url = imgArray.getJSONObject(i).getString("imageUrl")
//                            spaceDetail!!.imgList.add(url)
                            val item = ImageModel().apply { img = imgArray.getJSONObject(i).getString("imageUrl") }
                            list.add(item)
                        }
                        runOnUiThread {
                            setDetail()
                            if (list.size == 0) {
                                imgBanner.visibility = View.GONE
                            } else {
                                imgBanner.visibility = View.VISIBLE
                            }
                            startBannerView(list)
                        }
                        LCLogger.d(TAG, "获取成功！,数据：$jsonObject")
                    } else {
                        LCBaseUtil.showToast(mContext, "获取失败，$msg")
                    }
                } catch (e: Exception) {
                    cancleProgress()
                    LCBaseUtil.showToast(mContext, "获取失败，" + e.message)
                    e.printStackTrace()
                }
            }
        })
    }

    /**
     * @time 2025/4/23  18:49
     * @desc 开启轮播图
     */
    private fun startBannerView(list: ArrayList<ImageModel>) {
        val bannerAdapter = SliderSpaceAdapter(mContext, list)
        imgBanner.adapter = bannerAdapter

        val handler = Handler(Looper.getMainLooper())
        val update: Runnable = object : Runnable {
            private var page = 0 // 当前页面索引，从0开始计数
            override fun run() {
                if (list.size != 0) {
                    page = (page + 1) % list.size // 循环显示图片
                    imgBanner.setCurrentItem(page, true) // 切换到下一项并平滑滚动
                }
                handler.postDelayed(this, 3000) // 每3秒切换一次图片
            }
        }
        handler.post(update)
    }

    private fun setDetail() {
        if (spaceDetail == null) {
            return
        }
        ttvName.text = spaceDetail!!.name
        if (isVip(spaceDetail!!.isVip)) {
            imgVip.visibility = View.VISIBLE
        } else {
            imgVip.visibility = View.GONE
        }
        ttvTime.text = spaceDetail!!.publishTime
        ttvLocation.text = spaceDetail!!.publishLocation
        ttvContent.text = spaceDetail!!.infoContent
        ttvLook.text = "浏览：" + spaceDetail!!.viewCount
//        ttvCall.text = spaceDetail!!.userPhone
        ttvCall.setOnClickListener {
//            if (userInfo?.isVip() == true) {
            BaseUtil.callPhone(mContext, spaceDetail!!.userPhone)
//            }
        }

        Glide.with(imgAvatar)
            .load(NetWorkConfig.NET_URL_IMA_ROOT+spaceDetail!!.avatarUrl)
            .transform(CenterCrop(), RoundedCorners(20))
            .placeholder(R.mipmap.img_user_default)
            .error(R.mipmap.img_user_default)
            .into(imgAvatar);

    }

    fun isVip(vip: String): Boolean {
        return !LCBaseUtil.isNull(vip) && "VIP".equals(vip, true)
    }

}